package command.client;

import client.ClientSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Conversation;
import model.MessageCommunication;

public class InviteUserToChatClient implements CommandClient {

    private ArrayList<String> userList;
    private String userInvites;
    private Conversation newConversation;

    public InviteUserToChatClient() {
    }

    public void setUserList(ArrayList<String> usersToInvite) {
        userList = usersToInvite;
    }

    public void setUserInvites(String userNickName) {
        userInvites = userNickName;
    }

    public void setNewConversation(Conversation conversation) {
        newConversation = conversation;
    }

    @Override
    public void execute(ClientSession clientSession, boolean isInvokedByTheServer) {
        try {
            if (isInvokedByTheServer) {
                MessageCommunication messageUser = (MessageCommunication) clientSession.getObjectInputStream().
                        readObject();
                MessageCommunication messageConversation = (MessageCommunication) clientSession.getObjectInputStream().
                        readObject();
                userInvites = messageUser.getMessage();
                String conversationID = messageConversation.getMessage();
                clientSession.getGUIChatPrincipal().newInvitationToChat(userInvites, conversationID, clientSession);
            } else {
                clientSession.getObjectOutputStream().writeObject(new MessageCommunication(true, "inviteusertochatserver"));
                clientSession.getObjectOutputStream().flush();
                clientSession.getObjectOutputStream().writeObject(userList);
                clientSession.getObjectOutputStream().flush();
                clientSession.getObjectOutputStream().writeObject(new MessageCommunication(true, userInvites));
                clientSession.getObjectOutputStream().flush();
                clientSession.getObjectOutputStream().writeObject(newConversation);
                clientSession.getObjectOutputStream().flush();
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(InviteUserToChatClient.class.getName()).log(Level.SEVERE,
                    "Fallo al invitar a un usuario a unirse a una conversación en el cliente", ex);
        }
    }
}
